package com.genghis.rapidcrm.web.view.menu;

import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author xulixin
 */
@Component
public class RapidMenuModelProvider {

    @SuppressWarnings("unchecked")
    public List<RapidMenuModel> getAll(boolean raw) {
        YamlMapFactoryBean yaml = new YamlMapFactoryBean();
        yaml.setResources(new ClassPathResource("/config/rapidcrm-menu-repos.yaml"));
        Map<String, Object> moduleRepoMap = yaml.getObject();
        Map moreMenu = (Map) moduleRepoMap.get("modules");
        List list = new ArrayList();
        moreMenu.forEach((key, value) -> {
            if (value instanceof Collection) {
                Collection collection = (Collection) value;
                for (Object obj : collection) {
                    Map<String, Object> map = toMap(obj);
                    if (map != null) {
                        map.put("parent", key);
                        list.add(map);
                    }
                }

            } else {
                list.add(value);
            }
        });
        List<RapidMenuModel> allMenus = new ArrayList<>(list.size());
        for (Object obj : list) {
            if (obj instanceof Map) {
                allMenus.add(toMenuModel((Map) obj));
            }
        }
        return allMenus;
    }

    @SuppressWarnings("unchecked")
    private Map<String, Object> toMap(Object object) {
        if (object instanceof Map) {
            Map<String, Object> result = new LinkedHashMap<>();
            Map<Object, Object> map = (Map<Object, Object>) object;
            map.forEach((key, value) -> {
                if (key instanceof CharSequence) {
                    result.put(key.toString(), value);
                } else {
                    result.put(String.valueOf(key), value);
                }
            });
            return result;
        }
        return null;
    }

    private RapidMenuModel toMenuModel(Map map) {
        RapidMenuModel model = new RapidMenuModel();
        model.setLabel(String.valueOf(map.get("label")));
        model.setName(String.valueOf(map.get("name")));
        model.setDefaultUrl(String.valueOf(map.get("defaultUrl")));
        model.setTabSequence(0);
        model.setParent(String.valueOf(map.get("parent")));
        return model;
    }
}
